<script setup lang="ts">
import type { UploadInstance, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { useJsonStore } from '~/stores/json'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:visible', 'file-uploaded'])

const jsonStore = useJsonStore()
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit('update:visible', value),
})

const fileList = ref<UploadUserFile[]>([])
const upload = ref<UploadInstance>()
const loading = ref(false)

function readFile() {
  const reader = new FileReader()

  reader.onloadstart = () => {
    // ElMessage.info('开始读取文件...')
    loading.value = true
  }

  reader.onload = (e) => {
    try {
      const content = e.target?.result as string
      // console.warn(content)
      // 设置到store
      jsonStore.setSource(content)
      loading.value = false
      // ElMessage.success(`文件读取成功`)
      dialogVisible.value = false
    }
    catch (error) {
      console.error('文件处理错误:', error)
      ElMessage.error(`文件解析失败: ${error instanceof Error ? error.message : String(error)}`)
    }
  }
  reader.onerror = () => {
    ElMessage.error('文件读取失败，请重试')
  }
  reader.onabort = () => {
    ElMessage.warning('文件读取已取消')
  }
  const file = fileList.value[0]
  if (!file) {
    ElMessage.error('请先选择文件')
    return
  }
  if (file.raw) {
    reader.readAsText(file.raw as File)
  }
  else {
    reader.readAsText(file as File)
  }
}

function handleExceed(files: File[]) {
  const lastFile = files[files.length - 1]
  fileList.value = [lastFile as UploadUserFile]
}

function handleBeforeUpload() {

}
</script>

<template>
  <div>
    <el-dialog v-model="dialogVisible" title="上传文件" width="500">
      <el-upload
        ref="upload" v-model:file-list="fileList" drag :auto-upload="false" :limit="1"
        :on-exceed="handleExceed" :before-upload="handleBeforeUpload"
      >
        <el-icon class="el-icon--upload">
          <span i-carbon:add-large />
        </el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传JSON文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="readFile">
            <span v-loading="loading" />读取文件
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
